<template lang="pug">
.index
  .index-swiper
    .index-swiper-header
      .index-swiper-more(@click="seeMore") 查看更多>>
    .index-swiper-container
      .swiper-container
        .swiper-wrapper
          .swiper-slide(v-for="item, index in banner")
            .swiper-slide-material(:style="`background-image: url(${item.mainFileUrl})`")
            .swiper-slide-footer
              .material-name {{item.sampleName}}
              .material-brand 品牌：{{item.sampleBrandsName}}
              .material-cate 分类：{{item.sampleCategoryNamePath}}
              .material-link
                router-link.material-link-btn(:to="{ name: 'detail', params: { id: item.materialsSampleId } }" target="_blank")
                  .material-link-text 了解详情
                  .iconfont.icon-right
        .swiper-pagination
  select-device(:show="showDeviceDialog" @confirm="confirmSelectDevice")
</template>

<script>
import { getHotSampleList, getDoQuery } from 'api'
import selectDevice from '@/components/modal/selectDevice'
import Swiper from 'swiper'// 注意引入的是Swiper
let timer = null
export default {
  name: 'index',
  data () {
    return {
      showDeviceDialog: true,
      banner: [],
      deviceId: '',
      timeout: 55000, // 55秒发一次心跳，比nginx代理端默认连接超时时间（1分钟）稍微小一点，在接近断开的情况下以通信的方式去重置连接时间
      serverTimeoutObj: null,
      websocket_connected_count: 0, //已尝试连接次数
    }
  },
  watch: {
    deviceId (newVal, OldVal) {
      if (newVal) {
        const routerUrl = this.$router.resolve({
          name: 'detail',
          params: { id: newVal }
        })
        window.open(routerUrl.href, '_blank')
      }
    }
  },
  components: {
    selectDevice
  },
  methods: {
    seeMore () {
      const routerUrl = this.$router.resolve({
        name: 'list'
      })
      window.open(routerUrl.href, '_blank')
      // this.$router.push({ name: 'list' })
    },
    confirmSelectDevice (active) {
      this.showDeviceDialog = false
      this.createWebsocket(active)
    },
    createWebsocket(active) {
      let port;
      switch(active) {
        case 1:
            port = 8092;
            break;
        case 2:
            port = 8093;
            break;
        case 3:
            port = 8094;
            break;
      }
      const clientId = port + '@' + new Date().getTime();
      const httpURL = process.env.NODE_ENV === 'production' ? 'wss://henyouliao.cn' : 'ws://192.168.31.126:8005';
      this.websocket = new WebSocket(`${httpURL}/websocket/${clientId}`);
      // 连接发生错误的回调方法，连接错误时会继续尝试发起连接（尝试5次）
      this.websocket.onerror = () => {
        console.log("websocket发生了错误" + (this.websocket_connected_count > 0 ? "，已重连" + this.websocket_connected_count + "次" : ""));
        if( ++this.websocket_connected_count <= 5) {
          this.createWebsocket(active);
        }
      };
      // 连接成功建立的回调方法
      this.websocket.onopen = () => {
        console.log("websocket已打开(" + new Date().format('yyyy-MM-dd hh:mm:ss') + ")");
        //成功建立连接后，重置心跳检测
        this.heartCheckReset();
        this.heartCheckStart(active);
      };
      // 接收到消息的回调方法
      this.websocket.onmessage = (msg) => {
        //如果获取到消息，说明连接是正常的，重置心跳检测
        this.heartCheckReset();
        this.heartCheckStart(active);
        //拿到后端返回的心跳pong说明连接正常
        if(msg.data && String(msg.data).toLowerCase().trim() !== "pong") {
          console.log('websocket接收到消息', msg.data);
          const dataArr = JSON.parse(msg.data);
          dataArr.length == 1 && (this.deviceId = dataArr[0]);
        }
      };
      // 连接关闭的回调方法
      this.websocket.onclose = () => {
        console.log("websocket已关闭(" + new Date().format('yyyy-MM-dd hh:mm:ss') + ")");
      };
      // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
      this.websocket.onbeforeunload = () => {
        console.log('监听到窗口关闭事件，主动关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常');
        this.websocket.close();
        this.heartCheckReset();
      };
    },
    // 心跳检测, 每隔一段时间检测连接状态，如果处于连接中，就向server端主动发送消息，来重置server端与客户端的最大连接时间，如果已经断开了，发起重连。
    heartCheckReset() {
      clearTimeout(this.serverTimeoutObj);
    },
    heartCheckStart(active) {
      this.serverTimeoutObj = setTimeout(() =>{
        if(this.websocket.readyState == 1){
          console.log("websocket连接状态，发送心跳检测ping维持心跳连接...");
          this.websocket.send("ping");
          //如果获取到消息，说明连接是正常的，重置心跳检测
          this.heartCheckReset();
          this.heartCheckStart(active);
        } else {
          console.log("websocket断开状态，尝试重连");
          this.createWebsocket(active);
        }
      }, this.timeout)
    },
    longLink (active) {
      timer = setInterval(async () => {
        try {
          const { ResultSet } = await this.$axios.get(getDoQuery, { params: { number: active } })
          if (ResultSet.userData.data.length) this.deviceId = ResultSet.userData.data[0]
        } catch (err) {
          // clearInterval(timer)
          // this.message({ show: true, content: err.message || err.ResultSet.errors })
        }
      }, 1000)
    },
    async getList () {
      try {
        const { ResultSet } = await this.$axios.post(getHotSampleList)
        this.banner = ResultSet.userData.data
        this.$nextTick(() => {
          this.init()
        })
      } catch (err) {
        console.log(err)
      }
    },
    init () {
      new Swiper('.swiper-container', { // 参数配置：具体可以参考官网的API
        loop: true,
        grabCursor: true, // 该选项给Swiper用户提供小小的贴心应用，设置为true时，鼠标覆盖Swiper时指针会变成手掌形状，拖动时指针会变成抓手形状。（根据浏览器形状有所不同）
        centeredSlides: true, // 设定为true时，active slide会居中，而不是默认状态下的居左
        pagination: { //分页器的类
          el: '.swiper-pagination',
          type: 'fraction'
        },
        rewind: true,
        slidesPerView: 'auto', //  根据slide的宽度自动调整展示数量。此时需要设置slide的宽度，如下style所示
      })
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.getList()
    })
  }
}
</script>

<style lang="scss" scoped>

.index {
  height: 100%;
}
.index-swiper {
  height: 100%;
}
.index-swiper-header {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
.index-swiper-more {
  font-size: 16px;
  height: 22px;
  color: #CD9E78;
  cursor: pointer;
  padding: 0 20px;
  text-align: right;
}
.index-swiper-container {
  height: calc(100% - 42px);
  padding: 20px 0 0 0;
}
.swiper-container {
  height: 100%;
}
.swiper-slide-material {
  // width: 100%;
  // height: calc(100% - 160px);
  width: 700px;
  height: 500px;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  margin: 0 auto;
}
.swiper-slide-footer {
  padding-top: 20px;
  text-align: center;
  .material-name {
    font-size: 18px;
    font-weight: bold;
  }
  .material-brand {
    font-size: 16px;
  }
  .material-cate {
    font-size: 16px;
  }
  .material-link {
    margin-top: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    .material-link-btn {
      font-size: 18px;
      color: #CD9E78;
      display: flex;
      align-items: center;
    }
    .material-link-text {
      cursor: pointer;
    }
    .iconfont {
      margin-left: 5px;
    }
  }
}
.swiper-pagination {
  font-size: 16px;
}
</style>
